/*
 * $Id: MethodCacheInterceptor.java,v 1.2 2009/01/25 19:25:49 afaichun Exp $
 * 
 * Copyright (C) 2008 General Electric Company. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 * 
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */
package com.ge.healthcare.autosc.common.util;

import java.io.Serializable;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import com.ge.healthcare.autosc.common.ASCLogger;
/**
 * 
 * @author 212042946
 *
 */
public class MethodCacheInterceptor implements MethodInterceptor,
		InitializingBean {

	private Cache cache;

	/**
	   * main method
	   * caches method result if method is configured for caching
	   * method results must be serializable
	   */
	public Object invoke(MethodInvocation invocation) throws Throwable {
	    String targetName  = invocation.getThis().getClass().getName();
	    String methodName  = invocation.getMethod().getName();
	    Object[] arguments = invocation.getArguments();
	    Object result;

	    ASCLogger.debug(this.getClass(), "invoke", "looking for method result in cache");
	    String cacheKey = getCacheKey(targetName, methodName, arguments);
	    Element element = cache.get(cacheKey);
	    if (element == null) {
	      //call target/sub-interceptor
	      ASCLogger.debug(this.getClass(), "invoke", "calling intercepted method");
	      result = invocation.proceed();

	      //cache method result
	      ASCLogger.debug(this.getClass(), "invoke", "caching result");
	      element = new Element(cacheKey, (Serializable) result);
	      cache.put(element);
	    }
	    return element.getValue();
	}

	public void afterPropertiesSet() throws Exception {
		ASCLogger.debug(this.getClass(), "afterPropertiesSet", "Check wired object.");
		Assert.notNull(cache, "Cache object is required. Use setCache(Cache) to provide one.");
	}

	public void setCache(Cache cache) {
		this.cache = cache;
	}
	
	/**
	   * creates cache key: targetName.methodName.argument0.argument1...
	   */
	  private String getCacheKey(String targetName,
	                             String methodName,
	                             Object[] arguments) {
	    StringBuffer sb = new StringBuffer();
	    sb.append(targetName)
	      .append(".").append(methodName);
	    if ((arguments != null) && (arguments.length != 0)) {
	      for (int i=0; i<arguments.length; i++) {
	        sb.append(".")
	          .append(arguments[i]);
	      }
	    }

	    return sb.toString();
	  }
}
